#!/bin/bash
# 简单启动前端和后端，并实时显示日志

echo "=========================================="
echo "   CMDB - 启动所有服务"
echo "=========================================="
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 创建日志目录
mkdir -p logs
rm -rf logs/backend.log 2>/dev/null
rm -rf logs/frontend.log 2>/dev/null
touch logs/backend.log
touch logs/frontend.log

# 检查虚拟环境
if [ ! -d ".venv" ]; then
    echo "❌ 虚拟环境不存在，请先运行: bash deploy.sh"
    exit 1
fi

# 激活虚拟环境
. .venv/bin/activate

# 启动后端
echo "🚀 启动后端服务..."
cd backend
daphne -b 0.0.0.0 -p 8000 backend.asgi:application > ../logs/backend.log 2>&1 &
BACKEND_PID=$!
echo $BACKEND_PID > ../logs/backend.pid
cd ..
echo "  后端 PID: $BACKEND_PID"

# 启动前端
echo "🚀 启动前端服务..."
cd frontend
npm run dev > ../logs/frontend.log 2>&1 &
FRONTEND_PID=$!
echo $FRONTEND_PID > ../logs/frontend.pid
cd ..
echo "  前端 PID: $FRONTEND_PID"

# 等待服务启动
echo ""
echo "⏳ 等待服务启动..."
sleep 5

echo ""
echo "=========================================="
echo "   ✅ 服务已启动"
echo "=========================================="
echo ""
echo "📊 服务信息:"
echo "  前端: http://localhost:8080 (PID: $FRONTEND_PID)"
echo "  后端: http://localhost:8000 (PID: $BACKEND_PID)"
echo ""
echo "🔍 实时日志 (Ctrl+C 退出查看，服务继续运行):"
echo "=========================================="
echo ""

# 同时显示两个日志
tail -f logs/backend.log logs/frontend.log
